import { useState, useEffect, useRef, useCallback } from 'react';
import { danmuOcclusionService } from '../services/danmuOcclusionService';

export interface DanmuWithOcclusion {
    id: number;
    text: string;
    color: string;
    duration: number;
    top: number;
    paused?: boolean;
    occluded?: boolean;
    occlusionRatio?: number;
}

export interface UseDanmuOcclusionOptions {
    enabled: boolean;
    debugMode?: boolean;
    checkInterval?: number;
    occlusionThreshold?: number;
    characterBounds?: {
        width: number;
        height: number;
        offsetY: number;
    };
}

export const useDanmuOcclusion = (
    danmus: Array<{ id: number; text: string; color: string; duration: number; top: number; paused?: boolean }>,
    options: UseDanmuOcclusionOptions
) => {
    const [danmusWithOcclusion, setDanmusWithOcclusion] = useState<DanmuWithOcclusion[]>([]);
    const danmuElementsRef = useRef<Map<number, HTMLElement>>(new Map());
    const lastUpdateTimeRef = useRef<number>(0);
    const animationFrameRef = useRef<number | undefined>(undefined);

    // 更新遮挡服务配置
    useEffect(() => {
        if (!danmuOcclusionService) return;

        danmuOcclusionService.updateConfig({
            debugMode: options.debugMode,
            checkInterval: options.checkInterval,
            occlusionThreshold: options.occlusionThreshold,
            characterBounds: options.characterBounds,
        });
    }, [options.debugMode, options.checkInterval, options.occlusionThreshold, options.characterBounds]);

    // 注册弹幕元素引用
    const registerDanmuElement = useCallback((id: number, element: HTMLElement | null) => {
        if (element) {
            danmuElementsRef.current.set(id, element);
        } else {
            danmuElementsRef.current.delete(id);
        }
    }, []);

    // 检测弹幕遮挡 - 简化版本，只用于调试
    const checkOcclusions = useCallback(() => {
        if (!options.enabled || !danmuOcclusionService) return;

        const currentTime = performance.now();

        setDanmusWithOcclusion(prevDanmus => {
            return prevDanmus.map(danmu => {
                const element = danmuElementsRef.current.get(danmu.id);
                if (!element) return danmu;

                try {
                    const occlusionResult = danmuOcclusionService.checkDanmuOcclusion(element, currentTime);
                    // 不再应用遮挡效果，只记录状态用于调试
                    return {
                        ...danmu,
                        occluded: occlusionResult.isOccluded,
                        occlusionRatio: occlusionResult.occlusionRatio,
                    };
                } catch (error) {
                    console.warn('弹幕遮挡检测失败:', error);
                    return danmu;
                }
            });
        });
    }, [options.enabled]);

    // 使用requestAnimationFrame进行实时检测
    useEffect(() => {
        if (!options.enabled) return;

        const animate = () => {
            const currentTime = performance.now();
            const timeSinceLastUpdate = currentTime - lastUpdateTimeRef.current;

            // 控制检测频率，避免过度计算
            if (timeSinceLastUpdate >= (options.checkInterval || 100)) {
                checkOcclusions();
                lastUpdateTimeRef.current = currentTime;
            }

            animationFrameRef.current = requestAnimationFrame(animate);
        };

        animationFrameRef.current = requestAnimationFrame(animate);

        return () => {
            if (animationFrameRef.current) {
                cancelAnimationFrame(animationFrameRef.current);
            }
        };
    }, [options.enabled, options.checkInterval, checkOcclusions]);

    // 同步弹幕数据
    useEffect(() => {
        setDanmusWithOcclusion(danmus.map(danmu => ({
            ...danmu,
            occluded: false,
            occlusionRatio: 0,
        })));
    }, [danmus]);

    // 清理资源
    useEffect(() => {
        const elementsRef = danmuElementsRef.current;
        return () => {
            elementsRef.clear();
            if (animationFrameRef.current) {
                cancelAnimationFrame(animationFrameRef.current);
            }
        };
    }, []);

    return {
        danmusWithOcclusion,
        registerDanmuElement,
        checkOcclusions,
    };
};